<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>AI助手</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
  <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    
    body {
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
      background: transparent;
      height: 100vh;
      overflow: hidden;
      margin: 0;
      padding: 0;
    }
    
    .electron-floating-chat-container {
      position: fixed;
      z-index: 9999;
      user-select: none;
      width: 100vw;
      height: 100vh;
      top: 0;
      left: 0;
      padding: 10px;
      box-sizing: border-box;
    }
    
    .electron-floating-chat-container.fullscreen {
      position: fixed !important;
      top: 2.5vh !important;
      left: 2.5vw !important;
      width: 95vw !important;
      height: 95vh !important;
      z-index: 10001 !important;
      transform: none !important;
      margin: 0 !important;
      padding: 0 !important;
    }
    
    .electron-floating-chat-container.pinned {
      z-index: 99999 !important;
      position: fixed !important;
    }
    
    .electron-floating-chat-window {
      background: white;
      border-radius: 12px;
      box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
      width: 400px;
      height: 850px;
      display: flex;
      flex-direction: column;
      overflow: hidden;
      transition: all 0.3s ease;
      border: 1px solid #e5e7eb;
      margin: 10px;
      position: relative;
    }
    
    .electron-floating-chat-window.fullscreen {
      width: 100% !important;
      height: 100% !important;
      position: relative !important;
      top: 0 !important;
      left: 0 !important;
      transform: none !important;
      z-index: 1 !important;
      border-radius: 12px !important;
      margin: 0 !important;
    }
    
    .electron-floating-chat-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 12px 16px;
      cursor: move;
      user-select: none;
      background: #f8fafc;
      border-bottom: 1px solid #e5e7eb;
      -webkit-app-region: drag;
      position: relative;
    }
    
    .agent-name {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      font-weight: 700;
      color: #374151;
      font-size: 16px;
      -webkit-app-region: drag;
      pointer-events: auto;
      z-index: 10;
    }
    
    .pin-btn {
      width: 32px;
      height: 32px;
      border: none;
      background: transparent;
      color: #6b7280;
      border-radius: 6px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      transition: all 0.2s ease;
      -webkit-app-region: no-drag;
    }
    
    .pin-btn:hover {
      background: #f3f4f6;
      color: #374151;
      transform: scale(1.1);
    }
    
    .pin-btn.pinned {
      color: #3b82f6;
      background: #eff6ff;
    }
    
    .pin-btn.pinned:hover {
      background: #dbeafe;
      color: #1d4ed8;
    }
    
    .electron-floating-chat-actions {
      display: flex;
      gap: 8px;
    }
    
    .action-btn {
      width: 32px;
      height: 32px;
      border: none;
      background: transparent;
      color: #6b7280;
      border-radius: 6px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      transition: all 0.2s ease;
      -webkit-app-region: no-drag;
    }
    
    .action-btn:hover {
      background: #f3f4f6;
      color: #374151;
    }
    
    .electron-floating-chat-content {
      flex: 1;
      overflow-y: auto;
      padding: 20px 24px;
      scrollbar-width: none;
      -ms-overflow-style: none;
      min-height: 0;
      max-height: calc(100% - 120px);
    }
    
    .electron-floating-chat-content::-webkit-scrollbar {
      display: none;
    }
    
    .electron-floating-chat-empty {
      text-align: center;
      padding: 40px 20px;
    }
    
    .empty-illustration {
      margin-bottom: 24px;
    }
    
    .hexagon-shape {
      width: 120px;
      height: 120px;
      margin: 0 auto;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      border-radius: 20px;
      display: flex;
      align-items: center;
      justify-content: center;
      position: relative;
      overflow: hidden;
    }
    
    .illustration-icon {
      font-size: 48px;
      color: white;
      z-index: 1;
    }
    
    .empty-message {
      font-size: 16px;
      color: #374151;
      margin: 0 0 24px;
      font-weight: 500;
    }
    
    .hot-searches {
      background: #f9fafb;
      border-radius: 8px;
      padding: 16px;
      text-align: left;
    }
    
    .hot-searches-title {
      font-size: 14px;
      font-weight: 600;
      color: #374151;
      margin: 0 0 12px;
    }
    
    .hot-searches-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
    }
    
    .hot-tag {
      background: white;
      border: 1px solid #e5e7eb;
      border-radius: 6px;
      padding: 6px 12px;
      font-size: 12px;
      color: #374151;
      cursor: pointer;
      transition: all 0.2s ease;
    }
    
    .hot-tag:hover {
      background: #f3f4f6;
      border-color: #d1d5db;
    }
    
    .electron-floating-chat-messages {
      display: flex;
      flex-direction: column;
      gap: 16px;
    }
    
    .electron-floating-message-item {
      display: flex;
      width: 100%;
    }
    
    .electron-floating-user-message {
      justify-content: flex-end;
    }
    
    .electron-floating-ai-message {
      justify-content: flex-start;
    }
    
    .electron-floating-message-bubble {
      max-width: 80%;
      padding: 12px 16px;
      border-radius: 12px;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    }
    
    .user-bubble {
      background: #f3f4f6;
      color: #374151;
    }
    
    .ai-bubble {
      background: white;
      border: 1px solid #e5e7eb;
      color: #374151;
    }
    
    .electron-floating-message-text {
      font-size: 14px;
      line-height: 1.5;
      word-wrap: break-word;
    }
    
    .electron-floating-message-footer {
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 12px;
      margin-top: 8px;
      padding-top: 8px;
      border-top: 1px solid #f3f4f6;
      flex-wrap: wrap;
    }
    
    .electron-floating-stats-info {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 12px;
      color: #6b7280;
      flex: 1;
      min-width: 0;
    }
    
    .electron-floating-stat-item {
      font-size: 12px;
      color: #6b7280;
    }
    
    .electron-floating-stat-separator {
      font-size: 12px;
      color: #d1d5db;
    }
    
    .electron-floating-action-buttons {
      display: flex;
      align-items: center;
      gap: 4px;
      flex-shrink: 0;
    }
    
    .electron-floating-action-btn {
      width: 24px;
      height: 24px;
      border: none;
      background: transparent;
      color: #9ca3af;
      border-radius: 4px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      transition: all 0.2s ease;
      font-size: 12px;
    }
    
    .electron-floating-action-btn:hover {
      background: #f3f4f6;
      color: #6b7280;
    }
    
    .electron-floating-loading-container {
      display: flex;
      align-items: center;
      gap: 12px;
      padding: 8px 0;
    }
    
    .electron-floating-loading-dots {
      display: flex;
      gap: 4px;
    }
    
    .electron-floating-dot {
      width: 6px;
      height: 6px;
      background-color: #9ca3af;
      border-radius: 50%;
      animation: electron-floating-bounce 1.4s infinite ease-in-out both;
    }
    
    .electron-floating-dot:nth-child(1) { animation-delay: -0.32s; }
    .electron-floating-dot:nth-child(2) { animation-delay: -0.16s; }
    .electron-floating-dot:nth-child(3) { animation-delay: 0s; }
    
    @keyframes electron-floating-bounce {
      0%, 80%, 100% {
        transform: scale(0);
        opacity: 0.5;
      }
      40% {
        transform: scale(1);
        opacity: 1;
      }
    }
    
    .electron-floating-loading-text {
      color: #6b7280;
      font-size: 14px;
      font-style: italic;
    }
    
    .input-container {
      padding: 20px;
      background: white;
      flex-shrink: 0;
    }
    
    .uploaded-files-floating {
      position: absolute;
      bottom: 150px;
      left: 20px;
      right: 20px;
      z-index: 1000;
      pointer-events: none;
    }
    
    .uploaded-files-floating .file-item {
      pointer-events: auto;
      opacity: 0.3;
      transition: opacity 0.3s ease;
    }
    
    .uploaded-files-floating.file-hovered .file-item {
      opacity: 1;
      transition: opacity 0.2s ease;
    }
    
    .file-item {
      display: inline-block;
      margin-right: 8px;
      position: relative;
    }
    
    /* 图片预览样式 */
    .file-item img {
      border-radius: 8px;
      border: 1px solid #e5e7eb;
      width: 64px;
      height: 64px;
      object-fit: cover;
      transition: transform 0.2s ease;
    }
    
    .file-item:hover img {
      transform: scale(1.05);
    }
    
    /* 文件卡片样式 */
    .file-card {
      display: flex;
      align-items: center;
      gap: 8px;
      padding: 12px 12px 12px 8px;
      background: rgba(255, 255, 255, 0.9);
      backdrop-filter: blur(4px);
      border-radius: 8px;
      border: 1px solid #e5e7eb;
      min-width: 0;
      max-width: 200px;
      box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
    }
    
    .file-icon {
      flex-shrink: 0;
      font-size: 18px;
      color: #6b7280;
      margin-left: 0px;
      margin-right: 4px;
    }
    
    .file-info {
      flex: 1;
      min-width: 0;
      max-width: 120px;
    }
    
    .file-name {
      font-weight: 500;
      font-size: 14px;
      color: #111827;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      max-width: 140px;
    }
    
    .file-size {
      font-size: 12px;
      color: #6b7280;
    }
    
    .file-remove-btn {
      position: absolute;
      top: -4px;
      right: -4px;
      width: 16px;
      height: 16px;
      background: #4b5563;
      color: white;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 12px;
      cursor: pointer;
      transition: all 0.2s ease;
      opacity: 0;
    }
    
    .file-item:hover .file-remove-btn {
      opacity: 1;
    }
    
    .file-remove-btn:hover {
      background: #ef4444;
    }
    
    /* 输入框容器样式 */
    .input-wrapper {
      background: white;
      border-radius: 8px;
      border: 1px solid #e5e7eb;
      padding: 8px;
    }
    
    .input-textarea {
      width: 100%;
      background: transparent;
      border: none;
      outline: none;
      color: #374151;
      font-size: 14px;
      resize: none;
      font-family: inherit;
      line-height: 1.5;
    }
    
    .input-textarea::placeholder {
      color: #9ca3af;
    }
    
    .input-footer {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding-top: 4px;
    }
    
    .input-actions {
      display: flex;
      align-items: center;
      gap: 8px;
    }
    
    .upload-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 32px;
      height: 32px;
      color: #9ca3af;
      background: transparent;
      border: none;
      border-radius: 6px;
      cursor: pointer;
      transition: all 0.2s ease;
      font-size: 14px;
    }
    
    .upload-btn:hover {
      color: #2563eb;
      background: #eff6ff;
    }
    
    .upload-btn:disabled {
      opacity: 0.5;
      cursor: not-allowed;
    }
    
    .upload-btn:disabled:hover {
      color: #9ca3af;
      background: transparent;
    }
    
    .input-info {
      display: flex;
      align-items: center;
      gap: 12px;
    }
    
    .input-length {
      font-size: 12px;
      color: #9ca3af;
    }
    
    .send-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 32px;
      height: 32px;
      background: #2563eb;
      color: white;
      border: none;
      border-radius: 6px;
      cursor: pointer;
      transition: all 0.2s ease;
      font-size: 14px;
    }
    
    .send-btn:hover {
      background: #1d4ed8;
    }
    
    .send-btn:disabled {
      opacity: 0.5;
      cursor: not-allowed;
    }
    
    .cancel-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 32px;
      height: 32px;
      background: #dc2626;
      color: white;
      border: none;
      border-radius: 6px;
      cursor: pointer;
      transition: all 0.2s ease;
      font-size: 14px;
    }
    
    .cancel-btn:hover {
      background: #b91c1c;
    }
    
    /* 隐藏 textarea 的滚动条 */
    textarea {
      scrollbar-width: none; /* Firefox */
      -ms-overflow-style: none; /* IE and Edge */
    }
    
    textarea::-webkit-scrollbar {
      display: none; /* Chrome, Safari, Opera */
    }
    
    /* 确保flex布局正常工作 */
    .input-footer {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
    
    .input-actions {
      display: flex;
      align-items: center;
    }
    
    .input-info {
      display: flex;
      align-items: center;
    }
    
    /* 文件列表容器 */
    .files-list {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
    }
    
    /* 确保按钮图标居中 */
    .upload-btn i,
    .send-btn i,
    .cancel-btn i {
      font-size: 14px;
    }
    
    /* 文件卡片布局 */
    .file-card {
      display: flex;
      align-items: center;
    }
    
    /* 确保删除按钮在正确位置 */
    .file-item {
      position: relative;
    }
    
    .file-item .file-remove-btn {
      position: absolute;
      top: -4px;
      right: -4px;
    }
    
    /* Markdown 样式 */
    .electron-floating-message-text h1,
    .electron-floating-message-text h2,
    .electron-floating-message-text h3,
    .electron-floating-message-text h4,
    .electron-floating-message-text h5,
    .electron-floating-message-text h6 {
      margin: 0.5em 0;
      font-weight: bold;
      line-height: 1.2;
    }
    
    .electron-floating-message-text h1 { font-size: 1.3em; }
    .electron-floating-message-text h2 { font-size: 1.2em; }
    .electron-floating-message-text h3 { font-size: 1.1em; }
    
    .electron-floating-message-text p {
      margin: 0.5em 0;
      line-height: 1.5;
    }
    
    .electron-floating-message-text ul,
    .electron-floating-message-text ol {
      margin: 0.5em 0;
      padding-left: 1.5em;
    }
    
    .electron-floating-message-text li {
      margin: 0.25em 0;
    }
    
    .electron-floating-message-text blockquote {
      margin: 0.5em 0;
      padding: 0.5em 1em;
      border-left: 4px solid #e5e7eb;
      background-color: #f9fafb;
      font-style: italic;
    }
    
    .electron-floating-message-text code {
      background-color: #f3f4f6;
      padding: 0.2em 0.4em;
      border-radius: 3px;
      font-family: 'Courier New', monospace;
      font-size: 0.9em;
    }
    
    .electron-floating-message-text pre {
      background-color: #f3f4f6;
      padding: 1em;
      border-radius: 6px;
      overflow-x: auto;
      margin: 0.5em 0;
      scrollbar-width: none;
      -ms-overflow-style: none;
    }
    
    .electron-floating-message-text pre::-webkit-scrollbar {
      display: none;
    }
    
    .electron-floating-message-text pre code {
      background: none;
      padding: 0;
    }
    
    .electron-floating-message-text a {
      color: #3b82f6;
      text-decoration: underline;
    }
    
    .electron-floating-message-text a:hover {
      color: #1d4ed8;
    }
    
    .electron-floating-message-text strong {
      font-weight: bold;
    }
    
    .electron-floating-message-text em {
      font-style: italic;
    }
  </style>
</head>
<body>
  <div class="electron-floating-chat-container" id="chatContainer">
    <div class="electron-floating-chat-window" id="chatWindow">
      <!-- 头部 -->
      <div class="electron-floating-chat-header" id="chatHeader">
        <button class="pin-btn" id="pinBtn" title="置顶窗口">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M12 2l-1.5 1.5L12 5l1.5-1.5L12 2z"/>
            <path d="M12 5v13"/>
            <circle cx="12" cy="20" r="2"/>
          </svg>
        </button>
        <div class="agent-name" id="agentName">AI助手</div>
        <div class="electron-floating-chat-actions">
          <button class="action-btn" id="fullscreenBtn" title="全屏">
            <i class="fas fa-expand"></i>
          </button>
          <button class="action-btn" id="closeBtn" title="关闭">
            <i class="fas fa-times"></i>
          </button>
        </div>
      </div>

      <!-- 主要内容区域 -->
      <div class="electron-floating-chat-content" id="chatContent">
        <!-- 空状态 -->
        <div id="emptyState" class="electron-floating-chat-empty">
          <div class="empty-illustration">
            <div class="hexagon-shape">
              <i class="fas fa-comments illustration-icon"></i>
            </div>
          </div>
          <p class="empty-message">即刻开启AI对话</p>
          
          <!-- 热门问题 -->
          <div class="hot-searches">
            <h4 class="hot-searches-title">热门问题</h4>
            <div class="hot-searches-tags">
              <span class="hot-tag">诺基亚5G网络解决方案</span>
              <span class="hot-tag">诺基亚企业通信服务</span>
              <span class="hot-tag">诺基亚云原生技术</span>
              <span class="hot-tag">诺基亚网络安全产品</span>
            </div>
          </div>
        </div>

        <!-- 对话列表 -->
        <div id="messagesContainer" class="electron-floating-chat-messages" style="display: none;">
        </div>
      </div>

      <!-- 已上传文件展示区域 - 悬浮显示 -->
      <div id="uploadedFiles" class="uploaded-files-floating" style="display: none;">
        <div class="flex flex-wrap gap-2">
          <div id="filesList" class="files-list"></div>
        </div>
      </div>

      <!-- 输入框部分 -->
      <div class="input-container">
        <div class="input-wrapper">
          <textarea
            id="messageInput"
            class="input-textarea"
            placeholder="请输入内容..."
            rows="3"
          ></textarea>
          
          <!-- 底部操作栏 -->
          <div class="input-footer">
            <!-- 左侧按钮 -->
            <div class="input-actions">
              <button
                id="imageUploadBtn"
                class="upload-btn"
                title="上传图片"
              >
                <i class="fas fa-image"></i>
              </button>
              <button
                id="fileUploadBtn"
                class="upload-btn"
                title="上传文件"
              >
                <i class="fas fa-file"></i>
              </button>
            </div>
            
            <!-- 右侧信息 -->
            <div class="input-info">
              <span id="inputLength" class="input-length">0/129024</span>
              <button
                id="sendBtn"
                class="send-btn"
                title="发送消息"
              >
                <i class="fas fa-arrow-up"></i>
              </button>
              <button
                id="cancelBtn"
                class="cancel-btn"
                title="取消发送"
                style="display: none;"
              >
                <i class="fas fa-times"></i>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <script>
    // 从URL参数获取agentId和agentName
    const urlParams = new URLSearchParams(window.location.search);
    const agentId = urlParams.get('agentId') || null;
    const agentName = urlParams.get('agentName') || 'AI助手';
    
    // 智能体配置信息
    let agentConfig = {
      agent_name: agentName,
      agent_state: "1",
      agent_id: agentId,
      llm_api: "",
      llm_prompt: "",
      llm_image: "n"
    };
    
    // 状态管理
    let messages = [];
    let isPinned = false;
    let isFullscreen = false;
    let isDragging = false;
    let dragStart = { x: 0, y: 0 };
    let position = { x: 100, y: 100 };
    let forceTopInterval = null;
    let uploadedFilesList = [];
    let isSending = false;
    let currentRequest = null;
    let fileHoverTimeout = null;
    let isFileHovered = false;
    
    // DOM元素
    const chatContainer = document.getElementById('chatContainer');
    const chatWindow = document.getElementById('chatWindow');
    const chatHeader = document.getElementById('chatHeader');
    const pinBtn = document.getElementById('pinBtn');
    const fullscreenBtn = document.getElementById('fullscreenBtn');
    const closeBtn = document.getElementById('closeBtn');
    const messageInput = document.getElementById('messageInput');
    const sendBtn = document.getElementById('sendBtn');
    const chatContent = document.getElementById('chatContent');
    const emptyState = document.getElementById('emptyState');
    const messagesContainer = document.getElementById('messagesContainer');
    const agentNameElement = document.getElementById('agentName');
    const imageUploadBtn = document.getElementById('imageUploadBtn');
    const fileUploadBtn = document.getElementById('fileUploadBtn');
    const uploadedFiles = document.getElementById('uploadedFiles');
    const filesList = document.getElementById('filesList');
    const inputLength = document.getElementById('inputLength');
    const cancelBtn = document.getElementById('cancelBtn');
    
    // 设置智能体名称
    if (agentNameElement) {
      agentNameElement.textContent = agentName;
      console.log('设置智能体名称:', agentName);
    }
    
    // 获取智能体配置信息
    async function loadAgentConfig() {
      if (!agentId) return;
      
      try {
        // 第一步：根据agent_id获取智能体配置
        const response = await fetch(`http://localhost:5000/selectAgentById/${agentId}`);
        if (response.ok) {
          const data = await response.json();
          console.log('✅ 第一步：获取智能体配置成功:', data);
          
          // 构建智能体配置
          agentConfig = {
            agent_name: data.agent_name || agentName,
            agent_state: data.agent_state || "1",
            agent_id: agentId,
            llm_api: data.llm_api || "",
            llm_prompt: data.llm_prompt || "",
            llm_image: data.llm_image || "y",
            llm_file: data.llm_file || "y",
            llm_internet: data.llm_internet || "y",
            llm_memory: data.llm_memory || "y",
            llm_knowledge: data.llm_knowledge || "",
            llm_maximum_length_of_reply: data.llm_maximum_length_of_reply || "2048",
            llm_carry_number_of_rounds_of_context: data.llm_carry_number_of_rounds_of_context || "30",
            llm_temperature_coefficient: data.llm_temperature_coefficient || "0.6"
          };
          console.log('✅ 智能体配置已构建:', agentConfig);
          
          // 根据配置更新上传按钮显隐
          updateUploadButtonsVisibility();
        } else {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
      } catch (error) {
        console.error('❌ 第一步：加载智能体配置失败:', error);
        // 使用默认配置
        agentConfig = {
          agent_name: agentName,
          agent_state: "1",
          agent_id: agentId,
          llm_api: "qwen-max",
          llm_prompt: "默认模板",
          llm_image: "y",
          llm_file: "y",
          llm_internet: "y",
          llm_memory: "y",
          llm_knowledge: "",
          llm_maximum_length_of_reply: "2048",
          llm_carry_number_of_rounds_of_context: "30",
          llm_temperature_coefficient: "0.6"
        };
        
        // 根据默认配置更新上传按钮显隐
        updateUploadButtonsVisibility();
      }
    }
    
    // 初始化
    async function init() {
      setupEventListeners();
      updateUI();
      setupElectronListeners();
      await loadAgentConfig();
      
      // 确保初始状态不置顶
      if (window.require) {
        const { ipcRenderer } = window.require('electron');
        ipcRenderer.send('set-always-on-top', false);
        console.log('初始化：设置窗口不置顶');
      }
    }
    
    // 文件上传功能
    function openImageUpload() {
      const input = document.createElement('input');
      input.type = 'file';
      input.accept = 'image/*';
      input.onchange = handleImageSelect;
      input.click();
    }
    
    function openFileUpload() {
      const input = document.createElement('input');
      input.type = 'file';
      input.onchange = handleFileSelect;
      input.click();
    }
    
    function handleImageSelect(e) {
      const file = e.target.files[0];
      if (file) {
        addUploadedFile(file, 'image');
      }
    }
    
    function handleFileSelect(e) {
      const file = e.target.files[0];
      if (file) {
        addUploadedFile(file, 'file');
      }
    }
    
    function addUploadedFile(file, type) {
      const fileObj = {
        id: Date.now(),
        name: file.name,
        size: file.size,
        type: type,
        file: file,
        preview: null
      };
      
      // 如果是图片，生成预览
      if (type === 'image') {
        const reader = new FileReader();
        reader.onload = (e) => {
          fileObj.preview = e.target.result;
          updateUploadedFilesDisplay();
        };
        reader.readAsDataURL(file);
      }
      
      uploadedFilesList.push(fileObj);
      updateUploadedFilesDisplay();
    }
    
    function removeUploadedFile(fileId) {
      uploadedFilesList = uploadedFilesList.filter(f => f.id !== fileId);
      updateUploadedFilesDisplay();
    }
    
    function clearAllFiles() {
      uploadedFilesList = [];
      updateUploadedFilesDisplay();
    }
    
    function updateUploadedFilesDisplay() {
      if (uploadedFilesList.length === 0) {
        uploadedFiles.style.display = 'none';
        return;
      }
      
      uploadedFiles.style.display = 'block';
      filesList.innerHTML = '';
      
      // 添加悬停事件监听器
      uploadedFiles.addEventListener('mouseenter', handleFileMouseEnter);
      uploadedFiles.addEventListener('mouseleave', handleFileMouseLeave);
      
      uploadedFilesList.forEach(file => {
        const fileItem = document.createElement('div');
        fileItem.className = 'file-item';
        
        if (file.type === 'image') {
          // 图片文件直接展示
          fileItem.innerHTML = `
            <img 
              src="${file.preview || ''}" 
              alt="preview"
            />
            <button 
              onclick="removeUploadedFile(${file.id})" 
              class="file-remove-btn"
            >
              ×
            </button>
          `;
        } else {
          // 非图片文件显示卡片
          fileItem.innerHTML = `
            <div class="file-card">
              <div class="file-icon">
                <i class="fas fa-file"></i>
              </div>
              <div class="file-info">
                <div class="file-name">${file.name}</div>
                <div class="file-size">${formatFileSize(file.size)}</div>
              </div>
              <button 
                onclick="removeUploadedFile(${file.id})" 
                class="file-remove-btn"
              >
                ×
              </button>
            </div>
          `;
        }
        
        filesList.appendChild(fileItem);
      });
    }
    
    // 格式化文件大小
    function formatFileSize(bytes) {
      if (bytes === 0) return '0 Bytes';
      const k = 1024;
      const sizes = ['Bytes', 'KB', 'MB', 'GB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }
    
    // 文件悬停处理
    function handleFileMouseEnter() {
      // 清除之前的定时器
      if (fileHoverTimeout) {
        clearTimeout(fileHoverTimeout);
        fileHoverTimeout = null;
      }
      isFileHovered = true;
      uploadedFiles.classList.add('file-hovered');
    }
    
    function handleFileMouseLeave() {
      // 设置延迟1秒后透明化
      fileHoverTimeout = setTimeout(() => {
        isFileHovered = false;
        uploadedFiles.classList.remove('file-hovered');
      }, 1000);
    }
    
    // 更新输入长度
    function updateInputLength() {
      const length = messageInput.value.length;
      inputLength.textContent = `${length}/129024`;
    }
    
    // 取消发送
    function cancelSend() {
      if (currentRequest) {
        currentRequest.abort();
        currentRequest = null;
      }
      
      // 立即移除所有加载状态的消息
      messages = messages.filter(message => !message.isLoading);
      
      // 重置发送状态
      isSending = false;
      sendBtn.style.display = 'flex';
      cancelBtn.style.display = 'none';
      sendBtn.innerHTML = '<i class="fas fa-arrow-up"></i>';
      sendBtn.title = '发送消息';
      
      // 更新UI
      updateUI();
      
      console.log('✅ 用户取消了发送请求');
    }
    
    // 根据agent配置控制上传按钮显隐
    function updateUploadButtonsVisibility() {
      if (!agentConfig) return;
      
      // 根据llm_image配置控制图片上传按钮
      if (agentConfig.llm_image === 'y' || agentConfig.llm_image === 'Y') {
        imageUploadBtn.style.display = 'flex';
        imageUploadBtn.disabled = false;
        imageUploadBtn.classList.remove('disabled');
      } else {
        imageUploadBtn.style.display = 'flex';
        imageUploadBtn.disabled = true;
        imageUploadBtn.classList.add('disabled');
      }
      
      // 根据llm_file配置控制文件上传按钮
      if (agentConfig.llm_file === 'y' || agentConfig.llm_file === 'Y') {
        fileUploadBtn.style.display = 'flex';
        fileUploadBtn.disabled = false;
        fileUploadBtn.classList.remove('disabled');
      } else {
        fileUploadBtn.style.display = 'flex';
        fileUploadBtn.disabled = true;
        fileUploadBtn.classList.add('disabled');
      }
      
      console.log('📁 上传按钮显隐控制:', {
        llm_image: agentConfig.llm_image,
        llm_file: agentConfig.llm_file,
        imageBtnEnabled: !imageUploadBtn.disabled,
        fileBtnEnabled: !fileUploadBtn.disabled
      });
    }
    
    // 设置Electron事件监听
    function setupElectronListeners() {
      if (window.require) {
        const { ipcRenderer } = window.require('electron');
        
        // 监听全屏状态变化
        ipcRenderer.on('fullscreen-changed', (event, isFullscreen) => {
          console.log('收到全屏状态变化:', isFullscreen);
          isFullscreen = isFullscreen;
          updateFullscreenUI();
        });
      }
    }
    
    // 更新全屏UI
    function updateFullscreenUI() {
      if (isFullscreen) {
        fullscreenBtn.innerHTML = '<i class="fas fa-compress"></i>';
        fullscreenBtn.title = '退出全屏';
      } else {
        fullscreenBtn.innerHTML = '<i class="fas fa-expand"></i>';
        fullscreenBtn.title = '全屏';
      }
    }
    
    // 设置事件监听器
    function setupEventListeners() {
      // 防止重复绑定事件监听器
      if (window.eventListenersSetup) {
        return;
      }
      window.eventListenersSetup = true;
      
      // 置顶按钮
      pinBtn.addEventListener('click', togglePin);
      
      // 全屏按钮
      fullscreenBtn.addEventListener('click', toggleFullscreen);
      
      // 关闭按钮
      closeBtn.addEventListener('click', closeWindow);
      
      // 发送按钮
      sendBtn.addEventListener('click', sendMessage);
      
      // 文件上传按钮
      imageUploadBtn.addEventListener('click', openImageUpload);
      fileUploadBtn.addEventListener('click', openFileUpload);
      
      
      // 拖拽功能由CSS的-webkit-app-region处理
      
      // 输入框事件
      messageInput.addEventListener('keydown', (e) => {
        if (e.key === 'Enter' && !e.shiftKey) {
          e.preventDefault();
          sendMessage();
        }
      });
      
      // 输入长度监听
      messageInput.addEventListener('input', updateInputLength);
      
      // 取消按钮
      cancelBtn.addEventListener('click', cancelSend);
      
      // 初始化输入长度
      updateInputLength();
      
      
      // 热门问题点击
      document.querySelectorAll('.hot-tag').forEach(tag => {
        tag.addEventListener('click', () => {
          messageInput.value = tag.textContent;
          sendMessage();
        });
      });
    }
    
    // 拖拽功能由CSS的-webkit-app-region处理，无需JavaScript
    
    // 切换置顶
    function togglePin() {
      isPinned = !isPinned;
      pinBtn.classList.toggle('pinned', isPinned);
      
      if (isPinned) {
        pinBtn.title = '取消置顶';
        // 使用Electron API设置置顶
        if (window.require) {
          const { ipcRenderer } = window.require('electron');
          ipcRenderer.send('set-always-on-top', true);
        }
      } else {
        pinBtn.title = '置顶窗口';
        // 取消置顶
        if (window.require) {
          const { ipcRenderer } = window.require('electron');
          ipcRenderer.send('set-always-on-top', false);
        }
      }
      
      // 短暂闪烁效果提示用户
      chatContainer.style.transform = 'scale(1.02)';
      chatContainer.style.transition = 'transform 0.15s ease';
      setTimeout(() => {
        chatContainer.style.transform = 'scale(1)';
        setTimeout(() => {
          chatContainer.style.transition = '';
        }, 150);
      }, 150);
    }
    
    // 置顶功能实现
    function enableForceTop() {
      // 清除之前的定时器
      if (forceTopInterval) {
        clearInterval(forceTopInterval);
      }
      
      // 立即设置置顶
      setForceTop();
      
      // 每100ms检查一次，确保置顶
      forceTopInterval = setInterval(() => {
        setForceTop();
      }, 100);
      
      // 监听页面可见性变化
      document.addEventListener('visibilitychange', handleVisibilityChange);
      window.addEventListener('focus', handleWindowFocus);
    }
    
    function disableForceTop() {
      // 清除定时器
      if (forceTopInterval) {
        clearInterval(forceTopInterval);
        forceTopInterval = null;
      }
      
      // 移除事件监听
      document.removeEventListener('visibilitychange', handleVisibilityChange);
      window.removeEventListener('focus', handleWindowFocus);
      
      // 恢复默认z-index
      chatContainer.style.zIndex = '9999';
    }
    
    function setForceTop() {
      if (isPinned) {
        // 使用最大z-index值
        chatContainer.style.zIndex = '2147483647';
        chatContainer.style.position = 'fixed';
        
        // 确保窗口可见
        if (chatContainer.style.display === 'none') {
          chatContainer.style.display = 'block';
        }
      }
    }
    
    function handleVisibilityChange() {
      if (!document.hidden && isPinned) {
        setForceTop();
      }
    }
    
    function handleWindowFocus() {
      if (isPinned) {
        setForceTop();
      }
    }
    
    // 切换全屏
    function toggleFullscreen() {
      isFullscreen = !isFullscreen;
      
      if (window.require) {
        const { ipcRenderer } = window.require('electron');
        console.log('发送全屏切换请求:', isFullscreen);
        ipcRenderer.send('toggle-fullscreen', isFullscreen);
        
        // 同时使用CSS全屏作为备用
        if (isFullscreen) {
          chatContainer.classList.add('fullscreen');
          chatWindow.classList.add('fullscreen');
          // 强制重置位置，防止吸附到底部
          setTimeout(() => {
            forceResetFullscreenPosition();
          }, 50);
        } else {
          chatContainer.classList.remove('fullscreen');
          chatWindow.classList.remove('fullscreen');
          // 退出全屏时也重置位置
          setTimeout(() => {
            forceResetFullscreenPosition();
          }, 50);
        }
      } else {
        // 浏览器环境
        if (isFullscreen) {
          chatContainer.classList.add('fullscreen');
          chatWindow.classList.add('fullscreen');
          // 强制重置位置，防止吸附到底部
          setTimeout(() => {
            forceResetFullscreenPosition();
          }, 50);
        } else {
          chatContainer.classList.remove('fullscreen');
          chatWindow.classList.remove('fullscreen');
          // 退出全屏时也重置位置
          setTimeout(() => {
            forceResetFullscreenPosition();
          }, 50);
        }
      }
      
      updateFullscreenUI();
    }
    
    // 强制重置全屏位置
    function forceResetFullscreenPosition() {
      if (isFullscreen) {
        chatContainer.style.position = 'fixed';
        chatContainer.style.top = '2.5vh';
        chatContainer.style.left = '2.5vw';
        chatContainer.style.width = '95vw';
        chatContainer.style.height = '95vh';
        chatContainer.style.transform = 'none';
        chatContainer.style.margin = '0';
        chatContainer.style.padding = '0';
        console.log('强制重置全屏位置');
      } else {
        // 退出全屏时重置为默认样式
        chatContainer.style.position = 'fixed';
        chatContainer.style.top = '0';
        chatContainer.style.left = '0';
        chatContainer.style.width = '100vw';
        chatContainer.style.height = '100vh';
        chatContainer.style.transform = 'none';
        chatContainer.style.margin = '0';
        chatContainer.style.padding = '0';
        console.log('重置退出全屏位置');
      }
    }
    
    // 关闭窗口
    function closeWindow() {
      if (window.require) {
        const { ipcRenderer } = window.require('electron');
        // 直接关闭当前窗口
        const { remote } = window.require('electron');
        if (remote && remote.getCurrentWindow) {
          remote.getCurrentWindow().close();
        } else {
          // 备用方法：发送关闭请求
          ipcRenderer.send('close-current-window');
        }
      } else {
        window.close();
      }
    }
    
    // 发送消息
    async function sendMessage() {
      console.log('🔍 sendMessage 被调用，当前状态:', { isSending, message: messageInput.value.trim() });
      
      const message = messageInput.value.trim();
      if (!message && uploadedFilesList.length === 0) return;
      
      if (isSending) {
        console.log('⚠️ 正在发送中，忽略重复调用');
        return;
      }
      isSending = true;
      
      // 更新发送按钮状态
      sendBtn.style.display = 'none';
      cancelBtn.style.display = 'flex';
      
      // 添加用户消息
      if (message) {
        addMessage(message, false);
      }
      
      // 清空输入框和文件
      messageInput.value = '';
      clearAllFiles();
      
      // 清空字数统计
      updateInputLength();
      
      // 添加加载状态
      const loadingId = addLoadingMessage();
      
      // 检查是否有agentId
      if (!agentId) {
        console.error('agentId 不存在');
        // 移除加载状态
        removeLoadingMessage(loadingId);
        // 重置发送状态
        isSending = false;
        sendBtn.style.display = 'flex';
        cancelBtn.style.display = 'none';
        sendBtn.innerHTML = '<i class="fas fa-arrow-up"></i>';
        sendBtn.title = '发送消息';
        return;
      }
      
      // 第二步：使用获取的配置发送消息
      try {
        // 确保智能体配置已加载
        if (!agentConfig.llm_api) {
          console.log('⚠️ 智能体配置未完全加载，重新加载...');
          await loadAgentConfig();
        }
        
        // 构造请求体，使用完整的智能体配置信息
        const payload = {
          ...agentConfig,
          message: message
        };
        
        console.log('✅ 第二步：发送消息请求体:', payload);
        
        // 创建AbortController用于取消请求
        const abortController = new AbortController();
        currentRequest = abortController;
        
        const response = await fetch(`http://localhost:5000/processAgent/${agentId}`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(payload),
          signal: abortController.signal
        });
        
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const data = await response.json();
        console.log('✅ 第二步：API响应成功:', data);
        
        // 移除加载状态
        removeLoadingMessage(loadingId);
        
        // 添加AI回复
        if (data && data.result) {
          addMessage(data.result, true, data.stats);
          console.log('✅ 消息已添加到聊天列表');
        } else {
          addMessage('抱歉，AI回复出现错误', true);
        }
        
      } catch (error) {
        // 如果是用户主动取消，不显示错误信息，直接返回
        if (error.name === 'AbortError') {
          console.log('✅ 用户取消了发送请求');
          return;
        }
        
        console.error('❌ 第二步：发送消息失败:', error);
        removeLoadingMessage(loadingId);
        addMessage('抱歉，请求失败，请稍后重试', true);
      } finally {
        // 重置发送状态（无论是否取消都要重置）
        isSending = false;
        sendBtn.style.display = 'flex';
        cancelBtn.style.display = 'none';
        sendBtn.innerHTML = '<i class="fas fa-arrow-up"></i>';
        sendBtn.title = '发送消息';
        currentRequest = null;
      }
    }
    
    
    // Markdown 渲染
    function renderMarkdown(content) {
      if (!content) return '';
      return marked.parse(content);
    }
    
    // 添加消息
    function addMessage(content, isAI, stats = null) {
      console.log('📝 添加消息:', { content: content.substring(0, 50) + '...', isAI, messageCount: messages.length });
      const messageId = Date.now() + Math.random();
      const message = { id: messageId, content, isAI, stats };
      messages.push(message);
      
      updateUI();
    }
    
    // 添加加载消息
    function addLoadingMessage() {
      const loadingId = Date.now() + Math.random();
      const loadingMessage = { 
        id: loadingId, 
        content: '', 
        isAI: true, 
        isLoading: true 
      };
      messages.push(loadingMessage);
      
      updateUI();
      return loadingId;
    }
    
    // 移除加载消息
    function removeLoadingMessage(loadingId) {
      messages = messages.filter(msg => msg.id !== loadingId);
      updateUI();
    }
    
    // 更新UI
    function updateUI() {
      // 设置置顶按钮初始状态
      pinBtn.classList.remove('pinned');
      pinBtn.title = '置顶窗口';
      
      // 显示/隐藏空状态
      if (messages.length === 0) {
        emptyState.style.display = 'block';
        messagesContainer.style.display = 'none';
      } else {
        emptyState.style.display = 'none';
        messagesContainer.style.display = 'flex';
      }
      
      // 渲染消息
      renderMessages();
    }
    
    // 渲染消息
    function renderMessages() {
      messagesContainer.innerHTML = '';
      
      messages.forEach(message => {
        const messageDiv = document.createElement('div');
        messageDiv.className = `electron-floating-message-item ${message.isAI ? 'electron-floating-ai-message' : 'electron-floating-user-message'}`;
        
        const bubbleDiv = document.createElement('div');
        bubbleDiv.className = `electron-floating-message-bubble ${message.isAI ? 'ai-bubble' : 'user-bubble'}`;
        
        if (message.isLoading) {
          bubbleDiv.innerHTML = `
            <div class="electron-floating-loading-container">
              <div class="electron-floating-loading-dots">
                <div class="electron-floating-dot"></div>
                <div class="electron-floating-dot"></div>
                <div class="electron-floating-dot"></div>
              </div>
              <span class="electron-floating-loading-text">AI 正在思考中...</span>
            </div>
          `;
        } else {
          const textDiv = document.createElement('div');
          textDiv.className = 'electron-floating-message-text';
          textDiv.innerHTML = renderMarkdown(message.content);
          bubbleDiv.appendChild(textDiv);
          
          // 如果是AI消息，添加统计信息和操作按钮
          if (message.isAI) {
            const footerDiv = document.createElement('div');
            footerDiv.className = 'electron-floating-message-footer';
            
            // 统计信息
            const statsInfo = document.createElement('div');
            statsInfo.className = 'electron-floating-stats-info';
            statsInfo.innerHTML = `
              <span class="electron-floating-stat-item">字数: ${message.content.length}</span>
              <span class="electron-floating-stat-separator">|</span>
              <span class="electron-floating-stat-item">输入token: ${message.stats ? message.stats.input_tokens || 0 : 0}</span>
              <span class="electron-floating-stat-separator">|</span>
              <span class="electron-floating-stat-item">输出token: ${message.stats ? message.stats.output_tokens || 0 : 0}</span>
            `;
            
            // 操作按钮
            const actionButtons = document.createElement('div');
            actionButtons.className = 'electron-floating-action-buttons';
            
            // 构建按钮HTML
            let buttonsHTML = `
              <button class="electron-floating-action-btn" title="复制" onclick="copyMessage(${message.id})">
                <i class="fas fa-copy"></i>
              </button>
            `;
            
            // 只有最新的AI消息才显示重新生成按钮
            if (isLatestAIMessage(message)) {
              buttonsHTML += `
                <button class="electron-floating-action-btn" title="重新生成" onclick="retryMessage(${JSON.stringify(message).replace(/"/g, '&quot;')})">
                  <i class="fas fa-redo"></i>
                </button>
              `;
            }
            
            buttonsHTML += `
              <button class="electron-floating-action-btn" title="获取智能体ID" onclick="showAgentId()">
                <i class="fas fa-id-card"></i>
              </button>
            `;
            
            actionButtons.innerHTML = buttonsHTML;
            
            footerDiv.appendChild(statsInfo);
            footerDiv.appendChild(actionButtons);
            bubbleDiv.appendChild(footerDiv);
          }
        }
        
        messageDiv.appendChild(bubbleDiv);
        messagesContainer.appendChild(messageDiv);
      });
      
      // 滚动到底部
      chatContent.scrollTop = chatContent.scrollHeight;
    }
    
    // 复制消息
    function copyMessage(messageId) {
      const message = messages.find(m => m.id === messageId);
      if (message) {
        navigator.clipboard.writeText(message.content).then(() => {
          console.log('消息已复制到剪贴板');
          // 可以添加一个提示
        }).catch(err => {
          console.error('复制失败:', err);
        });
      }
    }
    
    // 判断是否为最新的AI消息
    function isLatestAIMessage(message) {
      // 如果不是 AI 消息，直接返回 false
      if (!message.isAI) return false;

      // 获取所有 AI 消息，并按 id 排序（id 是时间戳）
      const aiMessages = messages.filter(m => m.isAI);
      
      // 找到最后一条 AI 消息
      const latestAIMessage = aiMessages.length > 0 ? aiMessages[aiMessages.length - 1] : null;

      // 判断当前消息是否为最新的一条 AI 消息
      return message.id === latestAIMessage?.id;
    }
    
    // 重新生成消息
    async function retryMessage(message) {
      if (!agentId) {
        console.error('agentId 不存在');
        return;
      }

      // 找到当前 AI 消息的索引
      const aiIndex = messages.findIndex(m => m.id === message.id);
      if (aiIndex === -1) return;

      // 立即撤销当前AI回复，替换为加载状态
      const loadingMessageId = Date.now() + Math.random();
      messages[aiIndex] = {
        id: loadingMessageId,
        content: '',
        isAI: true,
        isLoading: true
      };
      updateUI();

      // 找到对应的用户消息
      const userMessage = messages[aiIndex - 1];
      if (!userMessage || userMessage.isAI) {
        console.error('找不到对应的用户消息');
        return;
      }

      // 取消当前请求（如果有的话）
      if (currentRequest) {
        currentRequest.abort();
      }

      // 创建新的请求控制器
      const abortController = new AbortController();
      currentRequest = abortController;

      try {
        // 确保智能体配置已加载
        if (!agentConfig.llm_api) {
          console.log('⚠️ 智能体配置未完全加载，重新加载...');
          await loadAgentConfig();
        }

        // 构造请求体
        const payload = {
          ...agentConfig,
          message: userMessage.content
        };

        console.log('✅ 重新生成请求体:', payload);

        const response = await fetch(`http://localhost:5000/processAgent/${agentId}`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(payload),
          signal: abortController.signal
        });

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();
        console.log('✅ 重新生成请求成功:', data);


        // 替换加载消息为新的AI回复
        if (data && data.result) {
          messages[aiIndex] = {
            id: loadingMessageId,
            content: data.result,
            isAI: true,
            stats: data.stats
          };
        } else {
          console.warn('返回数据中缺少 result 字段');
          messages[aiIndex] = {
            id: loadingMessageId,
            content: '抱歉，重新生成失败，请稍后重试',
            isAI: true
          };
        }
      } catch (error) {
        // 如果是用户主动取消，不显示错误信息
        if (error.name === 'AbortError') {
          console.log('用户取消了重新生成请求');
          return;
        }
        
        console.error('❌ 重新生成失败:', error);
        
        // 替换加载消息为错误信息
        messages[aiIndex] = {
          id: loadingMessageId,
          content: '抱歉，重新生成失败，请稍后重试',
          isAI: true
        };
      } finally {
        // 重置请求状态
        currentRequest = null;
        updateUI();
      }
    }
    
    // 显示智能体ID
    function showAgentId() {
      if (agentId) {
        alert(`智能体ID: ${agentId}`);
      } else {
        alert('当前没有智能体ID');
      }
    }
    
    // 启动应用
    init();
  </script>
</body>
</html>

